package jrain.fw.core.boot;

import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

import jrain.fw.core.log.Logger;
import jrain.fw.core.log.LoggerFactory;
import jrain.fw.core.service.ctx.CtxService;
import jrain.fw.core.service.ctx.CtxServiceProvider;
import jrain.fw.core.utils.FwUtils;
import jrain.utils.collection.RDMap;
import jrain.utils.prop.PropUtils;

/**
 * <pre>
 * 作者：489088214@qq.com 
 * 描述： 业务启动加载
 * </pre>
 */
public class Launcher {

	private static final AtomicBoolean running = new AtomicBoolean(false);
	private static final Logger log = LoggerFactory.getLogger("boot");
	private static CtxService ctxService = null;

	public synchronized static void start(Map<String, Object> cfg) {
		if (!running.getAndSet(true)) {
			try {
				loaderCfg(cfg);
				ctxService = CtxServiceProvider.getContext();
			} catch (Throwable e) {
				log.error(e.getMessage(), e);
				System.exit(1);
			}
		}
	}

	public synchronized static void stop() {
		if (running.getAndSet(false)) {
			if (ctxService != null) {
				ctxService.destroy();
			}
		}
	}

	public synchronized static void restart() {
		if (running.get()) {
			ctxService.destroy();
			ctxService.init();
		}
	}

	private static void loaderCfg(Map<String, Object> cfg) {
		String prop = "META-INF/conf/rain.conf";
		Map<String, Object> newCfg = PropUtils.getClasspathConf(prop);
		// 使用外部配置文件，覆盖默认配置文件
		prop = "rain.conf";
		Map<String, Object> data = PropUtils.getClasspathConf(prop);
		newCfg.putAll(data);
		// 使用传入参的参数，覆盖配置文件
		if (cfg != null) {
			newCfg.putAll(cfg);
		}
		log.debug("{}={}", "cfgMap", newCfg);
		FwUtils.setFwCfg(new RDMap<>(newCfg));
	}

}
